package com.example.testcamera2;

import androidx.annotation.NonNull;
import android.content.Context;
import android.util.AttributeSet;
import android.view.TextureView;
import androidx.annotation.Nullable;
/**
 * @author CYGL
 * @date 2021/6/15
 * GitEE: gitee.com/cygl
 * Dsecription:
 */
public class FaceView extends TextureView {

    private int ratioW = 0;
    private int ratioH = 0;

    public FaceView(@NonNull Context context) {
        super(context);
    }

    public FaceView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public FaceView(@NonNull Context context, @Nullable AttributeSet attrs,
                              int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (ratioW == 0 || ratioH == 0) {
            setMeasuredDimension(width, height);
        } else {
            if (width < height * ratioW / ratioH) {
                setMeasuredDimension(width, width * ratioH / ratioW);
            } else {
                setMeasuredDimension(height * ratioW / ratioH, height);
            }
        }
    }

    /**
     * 设置TextureView的宽高比
     *
     * @param width
     * @param height
     */
    public void setAspectRation(int width, int height) {
        if (width < 0 || height < 0) {
            throw new IllegalArgumentException("The width or height must not be less than zero");
        }
        ratioW = height;
        ratioH = width;
        requestLayout();
    }
}
